﻿using GraphicCreations.Manager;
using GraphicCreations.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GraphicCreations.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(AccountModel model)
        {
            if (ModelState.IsValid)
            {
                using (GCDataContext dataContext = new GCDataContext())
                {
                    if (!dataContext.CheckUserExists(model.Username.ToLowerInvariant().Trim()).Value)
                    {
                        dataContext.CreateUser(model.Name, model.Username, model.EmailID, model.Password, "USER");
                        return RedirectToAction("Login");
                    }
                    else
                    {
                        ModelState.AddModelError("Username", "Username already used!");
                    }
                }
            }

            return View(model);
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            bool isvalid = false;
            if (ModelState.IsValid)
            {
                using (GCDataContext dataContext = new GCDataContext())
                {
                    var result = dataContext.VerifyUserLogin(model.Username.ToLowerInvariant().Trim(), model.Password);
                    foreach (var item in result)
                    {
                        Session["gcuser"] = string.Format("{0}~{1}", item.UserID, item.Name);
                        isvalid = true;
                    }
                }
            }

            if (isvalid)
            {
               return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("Username", "Invalid credentials");
                return View();
            }
        }
    }
}
